import formDataService from '../services/formDataService';
import visitMonthPlanModel from '../model/visitMonthPlanModel';
import dTalkApi from '../core/dTalkApi';
import consumerRecoderModel from '../model/consumerRecoderModel';
import storeRecoderModel from '../model/storeRecoderModel';
import excelExportModel from '../model/excelExportModel';
import * as moment from 'moment';
import userCheckInModel from '../model/userCheckInModel';
import storeInfoModel from '../model/storeInfoModel';
import addExportModel from '../model/addExportModel';
import addService from '../services/addService';
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
const schedule = require("node-schedule");

class ExportService{
    constructor(){}


    async add(){
       /*  addService.getEmplFromDD().catch(error=>{
            console.log('getEmplFromDD_Error',error.message);
        }); */
        //定时添加每天的报表数据
        let j = await schedule.scheduleJob('00 50 23 * * *', function () {
            exportService.addExcelExportData().catch(error=>{
                console.log('addExcelExportData_Error',error.message);
            });
        });

        let m = await schedule.scheduleJob('00 40 23 * * *', function () {
            exportService.addData().catch(error=>{
                console.log('addData_Error',error.message);
            });
        
        });

        //同步钉钉的部门中人员的数据
         /* 
            部门id: 44766074 error_json===> { errmsg: '您的服务器调用钉钉开放平台当前接口的所有请求都被暂时禁用了, 
            apiPath(/user/list), 从 2018-11-27 17:00:12到 2018-11-27 17:00:12 请求总次数超过了 300 次, 
            处罚将在 2018-11-27 17:00:13 结束.',errcode: 90002 }
            unhandledRejection undefined
        */
        let j2 = await schedule.scheduleJob('00 10 22 * * *', function () {
            addService.getEmplFromDD().catch(error=>{
                console.log('getEmplFromDD_Error',error.message);
            });
        });
    }

    //添加每一天的报表数据
    async addExcelExportData(){
        let access_token=await dTalkApiUtil.getAccessToken();
        let userList=await visitMonthPlanModel.distinct("userId",{'$and':[{userId:{$ne:null}},{userId:{$ne:''}},{user:{$ne:''}},{user:{$ne:null}}]});
        console.log(userList.length)
        let date=moment().format('YYYY-MM-DD');
        if (userList.length > 0) {
            for (let employeeindex = 0; employeeindex < userList.length; employeeindex++) {
                let it = userList[employeeindex];
                let employeeInfo = await dTalkApi.getUserDetail(it,access_token);
                let name:any=''
                if (employeeInfo&&employeeInfo.name) {
                    name=employeeInfo.name;
                }else{
                    let data5=await visitMonthPlanModel.findOne({userId:it,'$and':[{user:{$ne:null}},{user:{$ne:''}}]})
                    if(data5){
                      name=data5.user
                    }
                } 
                //客户计划拜访数量
                let plan_count = await visitMonthPlanModel.count({ userId: it, planDate: date, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                //客户实际拜访数量
                let count_visited_consumer = await consumerRecoderModel.count({ userid: it, planDate: date, comment: 2 })
                let count_visited_store = await storeRecoderModel.count({ userid: it, planDate: date })
                let count_visit = count_visited_consumer + count_visited_store;
                let consumerRate_:any = 0;
                if (plan_count == 0) {
                    consumerRate_ = 0;
                } else {
                    consumerRate_ = count_visit / plan_count;
                }
                //签到率
                let checkInCount = await userCheckInModel.distinct("date_",{ date_: date, userId: it, isCheckInNineAm: true })  //实际签到天数
                let plan_day_count = await visitMonthPlanModel.distinct("planDate", {planDate:date, userId: it ,"$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }]});
                //签到率
                let checkInRate_ = 0;
                if (plan_day_count.length>0) {
                    checkInRate_ = (checkInCount.length / plan_day_count.length);
                
                } else {
                    checkInRate_ = 0;
                }
                let user_data=await userCheckInModel.findOne({userId: it,date_:date})   //当天的签到时间
                let time2:any=''
                if(user_data){
                    let time_1=user_data.checkin_time
                    if(time_1){
                        time2=moment(time_1).format('HH:mm:ss')
                    }
                }
            
                //新客户
                //实际已经拜访的新客户数量
                let count_visited_new_consumer = await consumerRecoderModel.count({ planDate: date, userid: it, planType: '新拓展客户', comment: 2 });
                //计划拜访的新客户数量
                let count_plan_new_consumer = await visitMonthPlanModel.count({ planDate: date, userId: it, plantype: '新拓展客户', "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }, { planStatus: '写好拜访记录' }, { planStatus: '未写拜访记录' }] });
                let new_consumerRate_ = 0;
                if (count_plan_new_consumer == 0) {
                    new_consumerRate_ = 0;
                } else {
                    new_consumerRate_ = (count_visited_new_consumer / count_plan_new_consumer);
                }

                //出差频率
                //非BASE地签到天数
                let unBase_check = 0;
                let store_data = await storeRecoderModel.find({ userid: it, planDate: date, isChuchai: true });
                let con_data = await consumerRecoderModel.find({ userid: it, planDate: date, isChuchai: true, comment: 2 })
                if (store_data.length > 0 || con_data.length > 0) {
                    unBase_check = 1
                } else {
                    unBase_check = 0
                }

                //已拜访门店达标率与门店拜访进度
                //门店已经拜访的数量
                let plan_store = await storeRecoderModel.count({ userid: it, planDate: date, planType: '门店' })
                //门店已经拜访的数量中店铺达标的数量
                let count_store = await storeRecoderModel.count({ userid: it, planDate: date, planType: '门店', isListStandard: true });
                //已拜访门店拜访达标率
                let reachStoreRate:any = 0;
                if (plan_store == 0) {
                    reachStoreRate = 0;
                } else {
                    reachStoreRate = (count_store / plan_store);
                }
                //门店拜访进度
                //员工名下的所有的客户
                let conList = await consumerRecoderModel.distinct("consumerCode", { userid: it, comment: 1 });
                //员工名下的所有的门店
                let count_totalStore_oneEmployee = await storeInfoModel.count({ consumerCode: { $in: conList } });
                //门店拜访进度
                let shop_schedule:any = 0;
                if (count_totalStore_oneEmployee == 0) {
                    shop_schedule = 0;
                } else {
                    shop_schedule = (plan_store / count_totalStore_oneEmployee);
                }

                let ad=await excelExportModel.create({
                    userId:it,
                    userName:name,
                    date_:date,
                    visitCount_plan:plan_count,//计划拜访客户数量(一天)
                    actuall_visitCount:count_visit,//实际拜访数量
                    consumerRate:consumerRate_.toFixed(2), //客户拜访达成率(一天)

                    newConsumerRate:new_consumerRate_.toFixed(2), //新客户拜访达成率
                    newConsumerCount_plan:count_plan_new_consumer,//计划拜访新客户数量
                    newConsumerCount_visit:count_visited_new_consumer,//实际拜访新客户数量

                    checkInRate:checkInRate_.toFixed(2),//签到率
                    actuall_checkIn:checkInCount.length,//实际签到天数
                    checkInTime:time2,

                    unBase_check:unBase_check,

                    reachStandardRate:reachStoreRate.toFixed(2),//已拜访门店达标率
                    reachStandardStoreCount:count_store,//门店达标的数量

                    visitedStoreCount:plan_store,//已经拜访的门店数量

                    storeSchadule:shop_schedule.toFixed(2),//门店拜访进度
                    totalCountStore:count_totalStore_oneEmployee,//员工名下总的门店数量


                    year: moment(date).format('YYYY'),
                    month:  moment(date).format('MM'),
                    comment:1
                })
                console.log(ad,'date_date_date_date_',date,it,employeeindex)
            }
        }  
    }

    
    //添加addExporModel数据-----日均
    async addData(){
        let access_token=await dTalkApiUtil.getAccessToken();
        // let dateList=await formDataService.getDate2(1,13,'2018-06-01')
        let date=moment().format('YYYY-MM-DD')
        // console.log(dateList,'dateList')
        let data7=await addExportModel.distinct('name_id',{})
        // console.log(data7,'<---------------------长度11111')
        let data3=await dTalkApi.getUserList('63824079',access_token)
        let list_3:any[]=[]
        if(data3&&data3.userlist&&data3.userlist.length>0){
            for (let index_3 = 0; index_3 < data3.userlist.length; index_3++) {
                let empl = data3.userlist[index_3];
                list_3.push(empl.userid) 
            }
        }
        // console.log(list_3,'????????????????') 
        let areaList:any =[]
        if(data7.length>0){
            for (let index = 0; index < data7.length; index++) {
                let element = data7[index];
                let data8=await addExportModel.findOne({name_id:element,"$and":[{name_:{$ne:null}},{name_:{$ne:''}}]});
                areaList.push({
                    id:element,
                    name:data8.name_
                })
            }
        }
        // console.log(areaList,'<---------------------长度11111',areaList.length)
        if(areaList.length==0){
            let list_1=await visitMonthPlanModel.distinct('nation',{'$and':[{nation:{$ne:null}},{nation:{$ne:''}}]})
            let nation:any=''
            if(list_1.length>0){
                list_1.map(it=>{
                    nation=it
                })
            }
            let a2=await visitMonthPlanModel.findOne({nation:nation,'$and':[{nationName:{$ne:null}},{nationName:{$ne:''}}]},{nationName:1,_id:0})
            let data=await dTalkApi.getSondepIdList(nation,false,access_token)
            let modelList=data.deptNames;   //模块
            // let proList=await visitMonthPlanModel.distinct('provinceName',{'$and':[{provinceName:{$ne:null}},{provinceName:{$ne:''}}]})
            let data2=await dTalkApi.getSondepIdList(nation,true,access_token)
            for (let index = 0; index < data2.dept.length; index++) {
                let element = data2.dept[index];
                if(modelList.includes(element.name)){
                    continue;
                }
                areaList.push(element)
            }
            
        }
        console.log(areaList,'<------------------1',areaList.length)
        if(areaList.length>0){
            for (let index_4 = 0; index_4 < areaList.length; index_4++) {
                let element = areaList[index_4];
                let id=element.id;
                let name=element.name
                let userList3:any[]=[]         
                if(id=='63824079'){
                    userList3=list_3
                }else{
                    userList3=await visitMonthPlanModel.distinct('userId',{'$or':[{areaName:name},{provinceName:name}],'$and':[{userId:{$ne:null}},{userId:{$ne:''}}]})
                }
                let consumerCount_day=0
                for (let b = 0; b < userList3.length; b++) {
                    let user_id = userList3[b];
                    let count =await formDataService.getCountConsumer_one_employeeDate1ToDate2(user_id,date,date)
                    consumerCount_day+=count;
                }
                let count3:any=0;
                if(userList3.length>0){
                  let count2:any=consumerCount_day/userList3.length;
                  count3=count2.toFixed(2)*1
                }
                let e=await addExportModel.create({
                    name_id:id,
                    name_:name,
                    date_:date,
                    month:moment(date).format('MM'),
                    consumerCount_day:consumerCount_day,//日均
                    consumerCount_empl:count3,//人均    默认全部是0
                    comment:1
                })
                console.log(e,'e_e_e_e_e_e_',name,date,consumerCount_day,count3)               
            }
        } 
    }

    //添加addExporModel数据-----人均

    async addData2(){
        let access_token=await dTalkApiUtil.getAccessToken();
        let dateList=await formDataService.getDate2(1,13,'2018-06-01')
        // console.log(dateList,'dateList')
        let list_1=await visitMonthPlanModel.distinct('nation',{'$and':[{nation:{$ne:null}},{nation:{$ne:''}}]})
        let nation:any=''
        if(list_1.length>0){
            list_1.map(it=>{
                nation=it
            })
        }
        let a2=await visitMonthPlanModel.findOne({nation:nation,'$and':[{nationName:{$ne:null}},{nationName:{$ne:''}}]},{nationName:1,_id:0})
        let data=await dTalkApi.getSondepIdList(nation,false,access_token)
        let modelList=data.deptNames;   //模块
        // let proList=await visitMonthPlanModel.distinct('provinceName',{'$and':[{provinceName:{$ne:null}},{provinceName:{$ne:''}}]})
        let data2=await dTalkApi.getSondepIdList(nation,true,access_token)
        let areaList:any =[]
        for (let index = 0; index < data2.dept.length; index++) {
            let element = data2.dept[index];
            if(modelList.includes(element.name)){
                continue;
            }
            areaList.push(element)
        }
        console.log(areaList,'<------------------1',areaList.length)
        let data3=await dTalkApi.getUserList('63824079',access_token)
        let list_3:any[]=[]
        if(data3&&data3.userlist&&data3.userlist.length>0){
            for (let index_3 = 0; index_3 < data3.userlist.length; index_3++) {
                let empl = data3.userlist[index_3];
                list_3.push(empl.userid) 
            }
        }
        console.log(list_3,'????????????????')  
        if(areaList.length>0){
            for (let index_4 = 0; index_4 < areaList.length; index_4++) {
                let element = areaList[index_4];
                let id=element.id;
                let name=element.name
                let userList3:any[]=[]         
                if(id=='63824079'){
                    userList3=list_3
                }else{
                    userList3=await visitMonthPlanModel.distinct('userId',{'$or':[{areaName:name},{provinceName:name}],'$and':[{userId:{$ne:null}},{userId:{$ne:''}}]})
                }
                for (let a = 0; a < dateList.length; a++) {
                    let date = dateList[a];
                    let consumerCount_day=0
                    for (let b = 0; b < userList3.length; b++) {
                        let user_id = userList3[b];
                        let count =await formDataService.getCountConsumer_one_employeeDate1ToDate2(user_id,date,date)
                        consumerCount_day+=count;
                    }
                    let count:any=0;
                    if(userList3.length>0){
                        count=consumerCount_day/userList3.length
                    }
                   
                    let e=await addExportModel.update({name_id:id,name_:name,date_:date,
                        month:moment(date).format('MM'),
                        consumerCount_day:consumerCount_day,//日均
                        
                        comment:1
                    },{consumerCount_empl:count})
                    console.log(e,'e_e_e_e_e_e_',name,date,consumerCount_day)
                }              
            }
        } 
    }






}
let exportService=new ExportService();
export default exportService;